﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace MissionCenter
{

    public class SquareViewModel
    {
        public Brush Color { get; set; } // 正方形的颜色
        public string Content { get; set; } // 正方形的内容
    }
    /// <summary>
    /// Market.xaml 的交互逻辑
    /// </summary>
    public partial class Market : UserControl
    {
        public static string api = "";
        public static string token = "";
        public static JObject userinformation = null;
        public Market()
        {
            InitializeComponent();

            Loaded += Market_Loaded;
            dynamicSquarePanel.SquareSizeWidth = 210;
            dynamicSquarePanel.SquareSizeHeight = 130;
            dynamicSquarePanel.SquareMarginX = 10;
            dynamicSquarePanel.SquareMarginY = 10;
        }

        private void Market_Loaded(object sender, RoutedEventArgs e)
        {
            Thread thread = new Thread(() =>
            {
                getScript();
            });
            thread.IsBackground = true;
            thread.Start();
        }
        private async void getScript() {
            if (api == "")
            {
                return;
            }
            HttpClient client = new HttpClient();
            // 目标接口的URL
            string url = api+"/mscripts?page=1&pageSize=100";

            try
            {
                // 发送GET请求
                HttpResponseMessage response = await client.GetAsync(url);

                // 确保响应成功
                response.EnsureSuccessStatusCode();

                // 读取响应内容
                string responseBody = await response.Content.ReadAsStringAsync();

                // 输出响应内容
                Console.WriteLine(responseBody);


                //转化为Jarray
                JArray jArray = (JArray)JsonConvert.DeserializeObject(responseBody);
                // 假设我们要添加一定数量的正方形

                Dispatcher.Invoke(new Action(() =>
                {
                    dynamicSquarePanel.Children.Clear();
                    for (int i = 0; i < jArray.Count; i++)
                    {
                        var square = new MarketBlock(api,token,userinformation)
                        {
                            
                            Width = dynamicSquarePanel.SquareSizeWidth,
                            Height = dynamicSquarePanel.SquareSizeHeight,
                            Margin = new Thickness(0)
                        };
                        square.Information = jArray[i];
                        square.scriptName.Text = jArray[i]["script_name"].ToString();
                        square.scriptAuthor.Text = jArray[i]["nickname"].ToString();
                        square.scriptDecribe.Text= jArray[i]["introduce"].ToString();
                        dynamicSquarePanel.Children.Add(square);

                    }

                }));


            }
            catch (HttpRequestException e)
            {
                // 异常处理
                Console.WriteLine("\nException Caught!");
                Console.WriteLine("Message :{0} ", e.Message);
            }
        }





    }

    public class DynamicSquarePanel : Panel
    {
        public double SquareSizeWidth { get; set; } = 50; // 正方形的宽
        public double SquareSizeHeight { get; set; } = 50; // 正方形的高

        public double SquareMarginX { get; set; } = 1; // 正方形的边距
        public double SquareMarginY { get; set; } = 1; // 正方形的边距

        protected override Size MeasureOverride(Size availableSize)
        {
            foreach (UIElement child in Children)
            {
                child.Measure(new Size(SquareSizeWidth, SquareSizeHeight));
            }
            return base.MeasureOverride(availableSize);
        }

        protected override Size ArrangeOverride(Size finalSize)
        {
            int numSquaresInRow = Math.Max(1, (int)((finalSize.Width + SquareMarginX) / (SquareSizeWidth + SquareMarginX)));
            double actualSquareWidth = SquareSizeWidth + SquareMarginX;
            double totalWidth = actualSquareWidth * numSquaresInRow - SquareMarginX; // 减去最后一个正方形的边距
            double leftOverSpace = finalSize.Width - totalWidth;
            double leftMargin = leftOverSpace / 2;
            double x = leftMargin;
            double y = 0- SquareMarginY;
            double rowHeight = SquareSizeHeight;
            foreach (UIElement child in Children)
            {
                if (x + SquareSizeWidth > finalSize.Width - leftMargin) // 检查是否需要换行
                {
                    x = leftMargin; // 重置 x 到新的一行，并保持左右空白相等
                    y += SquareSizeHeight + SquareMarginY; // 增加 y 到新的一行
                }

                // 放置子元素
                child.Arrange(new Rect(x, y, SquareSizeWidth, SquareSizeWidth));
                x = x+ SquareSizeWidth + SquareMarginX; // 增加 x 到下一个正方形的位置
            }
            Height = y+ SquareSizeHeight*2 - SquareMarginY;
            return finalSize; // 返回最终确定的面板大小
        }
    }

}
